<template>
  <div class="pages inDepotEdit">
    <div class="pageLevel">
      <div class="operationBox tableSearch">
        <el-button v-if="showTab == '2'" type="primary" @click="submitForm( 'formdata')" size="mini">保存</el-button>
      </div>
      <el-form :model="formdata" ref="formdata" :rules="rules" label-width="120px" size="mini">
        <el-row>
          <el-col :span="6">
            <el-form-item label="单据日期：" prop="orderDate">
              <span v-if="showTab == '1'">{{formdata.orderDate}}</span>
              <el-date-picker v-if="showTab == '2'" v-model="formdata.orderDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择单据日期" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据号：">
              <span v-if="showTab == '1'">{{formdata.inCode}}</span>
              <el-input v-if="showTab == '2'" v-model="formdata.inCode" placeholder="单据号自动生成" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 表格 -->
      <div class="tableMain">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column type="index" label="#" width="55"></el-table-column>
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="goodsName" label="商品" align="center" width="200">
            <template slot-scope="scope">
              <span v-if="showTab == '1'">{{scope.row.goodsName}}</span>
              <el-input v-if="showTab == '2'" v-model="scope.row.goodsName" size="mini">
                <el-button type="primary" @click="changeGoods(scope.$index)" slot="append">选择</el-button>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="goodsBatchNumber" label="批次" align="center">
            <template slot-scope="scope" >
             <span v-if="scope.row.isBatch == '1'">{{scope.row.goodsBatchNumber}}</span>
             <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
            </template>
          </el-table-column>
         <!-- 集团订单新加功能5/31 -->
          <el-table-column prop="dateInProduced" label="生产日期" align="center" width="100">
            <template slot-scope="scope" >
             <span v-if="scope.row.isBatch == '1'">{{scope.row.dateInProduced}}</span>
             <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="warehouseName" label="仓库" align="center" width="200">
            <template slot-scope="scope">
              <span v-if="showTab == '1'">{{scope.row.warehouseName}}</span>
              <el-input v-if="showTab == '2'" v-model="scope.row.warehouseName" size="mini">
                <el-button type="primary" @click="showCang(scope.$index)" slot="append">选择</el-button>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
          <el-table-column prop="goodsSpec" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item, index) in scope.row.goodsSpec" :key="index" v-if='item'>
                <span>{{item.paramName}} :</span>
                <span>{{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsPrice" label="单价" align="center">
            <template slot-scope="scope">
              <span v-if="showTab == '1'">{{scope.row.goodsPrice}}</span>
              <sd-input v-if="showTab == '2'" :val.sync='scope.row.goodsPrice'></sd-input>
            </template>
          </el-table-column>
          <el-table-column prop="goodsNum" label="数量" align="center" width="150">
            <template slot-scope="scope">
              <span v-if="showTab == '1'">{{scope.row.goodsNum}}</span>
              <input class="commonInput" v-if="showTab == '2'" v-model="scope.row.goodsNum" size="mini" type="text" style="width:100px" value="1" min="0" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
            </template>
          </el-table-column>
          <el-table-column prop="goodsAmount" label="总价" align="center">
            <template slot-scope="scope">
              <span v-if="showTab == '1'">{{scope.row.goodsAmount}}</span>
              <span v-if="showTab == '2'">{{(Number(scope.row.goodsPrice)*Number(scope.row.goodsNum)).toFixed(2)}}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="showTab == '2'" align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.goodsName" @click="handleCancel(scope.$index)" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="th-right">
        <el-form :model="formdata" label-width="120px" size="mini">
          <el-row>
            <el-col :span="12">
              <el-form-item label="操作员：">
                <span v-if="showTab == '1'">{{formdata.creater}}</span>
                <el-input v-if="showTab == '2'" v-model="formdata.creater" disabled></el-input>
              </el-form-item>
              <el-form-item label="备注：">
                <span v-if="showTab == '1'">{{formdata.remark}}</span>
                <el-input v-if="showTab == '2'" v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总计：">
                <span v-if="showTab == '1'">{{formdata.inAmount}}</span>
                <el-input v-if="showTab == '2'" v-model="formdataTotal" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 商品选择弹出框 -->
      <el-dialog title="商品选择" class="addshopname" :visible.sync="dialogTableVisible_good" :closeOnClickModal='false' :closeOnPressEscape='false' width="60%">
        <i class="el-icon-close icon" @click="dialogTableVisible_good=false"></i>
        <div class="operationBox tableSearch">
          <el-button size="mini" type="primary" @click="save_good">选择</el-button>
          <el-button size="mini" @click="dialogTableVisible_good=false">取消</el-button>
        </div>
        <div class="tableSearch tableSearchs">
          <i class="el-input__icon el-icon-search" @click="searchSelect"></i>
          <el-form label-width="100px" class="demo-ruleForm">
            <el-form-item label="" label-width="15px">
              <el-input class="input" v-model="selectdatas.keyword" size="small" placeholder="输入商品名称或编号">
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="goodArray" stripe border ref="multipleTable" tooltip-effect="dark" @selection-change="changeFun_good">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="name" label="商品" align="center"></el-table-column>
          <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
          <el-table-column prop="goodsSpec" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item, index) in scope.row.goodsSpec" :key="index">
                <span>{{item.paramName}} :</span>
                <span>{{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="purchasePrice" label="单价" align="center"></el-table-column>
          <el-table-column prop="goodsQuantity" label="库存结余" align="center"></el-table-column>
        </el-table>
        <div class="pageblock">
          <el-button size="mini" type="primary" class="Determine topage">确定</el-button>
          <el-pagination @size-change="handleSizeChange_good" @current-change="handleCurrentChange_good" :current-page="currentpage_good" :page-sizes="[20,30]" :page-size="pageSize_good" layout="total, sizes, prev, pager, next, jumper" :total="total_good">
          </el-pagination>
        </div>
      </el-dialog>
      <!-- 仓库选择弹出框 -->
      <el-dialog title="仓库选择" class="addshopname" :visible.sync="dialogTableVisible_cang" :closeOnClickModal='false' :closeOnPressEscape='false' width="60%">
        <i class="el-icon-close icon" @click="dialogTableVisible_cang=false"></i>
        <div class="operationBox tableSearch">
          <el-button size="mini" type="primary" @click="save_cang">选择</el-button>
          <el-button size="mini" @click="dialogTableVisible_cang=false">取消</el-button>
        </div>
        <el-table :data="cangArray" stripe border ref="multipleTable" tooltip-effect="dark" highlight-current-row @current-change="changeFun_cang">
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="name" label="仓库" align="center"></el-table-column>
          <el-table-column prop="address" label="地址" align="center"></el-table-column>
        </el-table>
        <div class="pageblock">
          <el-button size="mini" type="primary" class="Determine topage">确定</el-button>
          <el-pagination @size-change="handleSizeChange_cang" @current-change="handleCurrentChange_cang" :current-page="currentpage_cang" :page-sizes="[20,30]" :page-size="pageSize_cang" layout="total, sizes, prev, pager, next, jumper" :total="total_cang">
          </el-pagination>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import sdInput from "@/components/SdInput";
import { mapState } from "vuex";
import u from "@/util";
import { getRepertoryInBoundDetail } from "@/api";
export default {
  components: { sdInput },
  computed: {
    ...mapState({
      sub: state => state.sub,
      merchantId: state => state.merchantId,
      companyName: state => state.companyName,
      userId:state => state.userId,
    }),
    formdataTotal: function() {
      let totalPrice = 0;
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].goodsAmount =
          this.tableData[i].goodsPrice * this.tableData[i].goodsNum;
        totalPrice += this.tableData[i].goodsPrice * this.tableData[i].goodsNum;
      }
      this.formdata.purchaseAmount = totalPrice.toFixed(2);
      return totalPrice.toFixed(2);
    }
  },
  data() {
    return {
      options: [],
      selectdata: {
        keyword: ""
      },
      selectdatas: {
        keyword: ""
      },
      changeGoodId: "",
      id: "",
      showTab: "",
      cang_index: "",
      tableData: [],
      rules: {
        warehouseId: [
          { required: true, message: "请选择入库仓库", trigger: "blur" }
        ],
        orderDate: [
          { required: true, message: "请选择单据时间", trigger: "blur" }
        ]
      },
      formdata: {
        inCode: "",
        warehouseName: "",
        warehouseId: "",
        warehouseId: "",
        orderDate: "",
        creater: "",
        remark: "",
        inAmount: "",
        purchaseinCode: ""
      },
      dialogTableVisible_good: false,
      dialogTableVisible_cang: false,
      selection_good: [],
      selection_cang: [],
      goodArray: [],
      cangArray: [],
      pageSize_good: 20,
      pageSize_cang: 20,
      currentpage_good: 1,
      currentpage_cang: 1,
      total_good: 0,
      total_cang: 0
    };
  },
  created() {
    this.id = u.getQuery("id");
    this.showTab = u.getQuery("status");
  },
  mounted() {
    this.getDataById();
    // this.getGoods(20, 1)
    // this.repertory()
  },
  methods: {
    repertory() {
      //---------仓库下拉
      let data = {
        orgId: this.compId
      };
      storeDownList(data).then(res => {
        this.options = res.data;
      });
    },
    //----------选择商品搜索
    searchSelect() {
      this.selectdata.keyword = this.selectdatas.keyword;
      this.getGoods(20, 1);
    },
    tim(row) {
      return u.foryear(parseInt(row.orderDate));
    },
    changeGoods(index) {
      this.changeGoodId = index;
      this.dialogTableVisible_good = true;
    },
    //------------查看详情
    getDataById() {
      let data = {
        id: this.id
      };

      // selectInBoundDetails(data).then(res => {
      //   this.formdata = res.data
      //   this.tableData = res.data.goodsList
      // })
      getRepertoryInBoundDetail(data).then(res => {
        this.formdata = res.data;
        this.formdata.orderDate = this.tim(this.formdata);
        this.tableData = res.data.goodsList;
        this.formdata.creater = res.data.userName;
      });
    },
    //-----------商品列表
    getGoods(pageSize, pageNum) {
      let data = {
        keyword: this.selectdata.keyword,
        pageSize: pageSize,
        pageNum: pageNum,
        orgId: this.compId,
        status: 0
      };
      findGoodsListPage(data).then(res => {
        this.goodArray = res.data.list;
        this.total_good = res.data.pageTotal;
      });
    },
    //-----------仓库列表
    getCang(pageSize, pageNum) {
      let data = {
        pageSize: pageSize,
        pageNum: pageNum,
        keyword: ""
      };
      findRepositoryListPage(data).then(res => {
        this.cangArray = res.data.list;
        this.total_cang = res.data.pageTotal;
      });
    },
    // 点击返回按钮
    goBack() {
      history.back();
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave();
        } else {
          return false;
        }
      });
    },
    // -----------点击修改
    handleEdit() {
      this.showTab = "2";
    },
    // ----------- 修改 保存
    handleSave() {
      if (this.tableData.length == 0) {
        this.$message({
          type: "error",
          message: "商品不能为空"
        });
        return false;
      }
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].goodsNum <= 0) {
          this.$message({
            type: "error",
            message: "商品数量不能小于等于0"
          });
          return false;
        }
      }
      for (let i = 0; i < this.options.length; i++) {
        if (this.options[i].id == this.formdata.warehouseId) {
          this.formdata.warehouseName = this.options[i].name;
        }
      }
      saveOrUpdateInBound({
        id: this.id,
        shopId: this.compId,
        shopName: this.companyName,
        warehouseId: this.formdata.warehouseId,
        warehouseName: this.formdata.warehouseName,
        orderDate: this.formdata.orderDate,
        creater: this.userId,
        inAmount: this.formdataTotal,
        inType: 0,
        goodsList: JSON.stringify(this.tableData)
      }).then(res => {
        this.$message({
          type: "success",
          message: "修改成功!"
        });
        this.$store.commit("SETISRELOADDATA", true);
        history.back();
      });
    },
    // -------------商品选择后
    save_good() {
      if (this.selection_good.length === 0) {
        this.$message({
          type: "error",
          message: "请先选择商品!"
        });
      } else {
        for (let i = 0; i < this.selection_good.length; i++) {
          this.selection_good[i].goodsName = this.selection_good[i].name;
        }
        this.tableData.splice(this.changeGoodId, 1);
        this.tableData = this.tableData.concat(this.selection_good);
        var allArr = [];
        for (var i = 0; i < this.tableData.length; i++) {
          var flag = true;
          for (var j = 0; j < allArr.length; j++) {
            if (this.tableData[i].skuCode == allArr[j].skuCode) {
              flag = false;
            }
          }
          if (flag) {
            allArr.push(this.tableData[i]);
          }
        }
        this.tableData = allArr;
        this.dialogTableVisible_good = false;
      }
    },
    save_cang() {
      let i = this.cang_index;
      this.tableData[i].repositoryId = this.selection_cang.name;
      this.dialogTableVisible_cang = false;
    },
    changeFun_good(val) {
      if (val) {
        this.selection_good = val;
      } else {
        this.selection_good = [];
      }
    },
    changeFun_cang(val) {
      if (val) {
        this.selection_cang = val;
      } else {
        this.selection_cang = [];
      }
    },
    showCang(index) {
      this.cang_index = index;
      this.dialogTableVisible_cang = true;
    },
    handleCancel(index) {
      this.tableData.splice(index, 1);
    },
    handleSizeChange_good(val) {
      this.pageSize_good = val;
      this.getGoods(val, this.currentpage_good);
    },
    handleSizeChange_cang(val) {
      this.pageSize_cang = val;
      this.getCang(val, this.currentpage_cang);
    },
    handleCurrentChange_good(val) {
      this.getGoods(this.pageSize_good, val);
    },
    handleCurrentChange_cang(val) {
      this.currentpage_cang = val;
      this.getCang(this.pageSize_cang, val);
    }
  }
};
</script>
<style scoped>
.th-right {
  float: right;
  margin-top: 20px;
  width: 50%;
  min-width: 300px;
}
.tableSearchs {
  position: relative;
}
.tableSearchs .el-input__icon {
  position: absolute;
  top: 12px;
  left: 190px;
  z-index: 10;
  width: 25px;
  height: 35px;
}
</style>
<style>
.el-input__inner {
  padding: 0 20px;
}
</style>

